﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using System.IO;


/* FUCKING BIG TODO LIST 
 * 
 * 
 * SAUVEGARDER PLUSIEURS LAYERS DANS LA MAP
 * AJOUTER LE SUPPORT POUR CHARGER PLUSIEURS LAYERS
 * FRAPPER CHRIS
 * 
 * 
 * */



namespace MapEditor
{
    public partial class frmEditor : Form
    {
        public Dictionary<int,Texture2D> list_Textures;
        public Dictionary<int, int> list_KeysTextures;
        public int _selectedIndex;
        public bool _IDChanged { get; set; }
        public bool _TextureDeleted { get; set; }
        public bool ShowGrid { get; set; }
        public int GetOldID { get; set; }
        public int GetNewID { get; set; }
        public int GetIDLayers { get; set; }


        private ContentManager content;
        private GraphicsDevice graphics;
        private List<Panel> listPanel;
       // private string[] files;
        private List<string> ListOfLoadedFiles;
        
        private int _numberOfTexture;
        int topItems = 30;
        int leftItems = 20;
        int topWalls = 30;
        int leftWalls = 20;
        int topTextures = 30;
        int leftTextures = 20;
        int width = 50;
        int height = 50;
        private Panel lastPanelClicked;
        private Panel PanelSelected;
        private Font myFont;
        private SolidBrush BrushBlack;
        private SolidBrush BrushWhite;
        private bool showID;


        public frmTools Tools { get; set; }

        public int MapWidth { get { return frmEd.MapWidth; } }
        public int MapHeight { get { return frmEd.MapHeight; } }

        public bool HasMapChangedDimensions { get; set; }

        public bool IsSaving { get; set; }
        public bool IsLoading { get; set; }
        public bool ExitSig { get; set; }
        public bool ClearSig { get; set; }

        frmEdit frmEd;

        //Property
        public Dictionary<int, Texture2D> Get_Dict
        {
            get { return list_Textures; }
        }

        
        public frmEditor(GraphicsDevice graphics, ContentManager content, int mapwidth, int mapheight)
        {

            InitializeComponent();
            this.graphics = graphics;
            list_Textures = new Dictionary<int, Texture2D>();
            list_KeysTextures = new Dictionary<int, int>();
            listPanel = new List<Panel>();
            ListOfLoadedFiles = new List<string>();
            this.content = content;
            _selectedIndex = 0;
            _numberOfTexture = 0;
            _TextureDeleted = false;
            _IDChanged = false;
            myFont = new Font("Arial",14);
            BrushBlack = new SolidBrush(Color.Black);
            BrushWhite = new SolidBrush(Color.White);
            showID = true;
            ShowGrid = true;
            GetIDLayers = 1;

            LoadDefaultTexture();

            frmEd = new frmEdit(mapwidth, mapheight);

        }

        //Methode, function
        private void frmEditor_FormClosing(object sender, FormClosingEventArgs e)
        {    
            e.Cancel = true;
            this.Visible = false;
        }

        private void EventPanel_Click(object sender, MouseEventArgs e)
        {
            
            if (lastPanelClicked != null)
                lastPanelClicked.BorderStyle = BorderStyle.None;

            _selectedIndex = Convert.ToInt32(((Panel)sender).Tag.ToString().Split('|')[0]);

            ((Panel)sender).BorderStyle = BorderStyle.Fixed3D;
            lastPanelClicked = ((Panel)sender);
        }

        private void EventPanel_Paint(object sender, PaintEventArgs e)
        {
            //string[] stringSplit = ((Panel)sender).Tag.ToString().Split('|');
            //bm = new Bitmap(stringSplit[stringSplit.Length - 1]);
            
            //e.Graphics.DrawImage(bm, new Rectangle(0, 0, ((Panel)sender).Width, ((Panel)sender).Height));
            if (showID)
            {
                e.Graphics.FillRectangle(BrushWhite, new Rectangle(0, ((Panel)sender).Height / 2, ((Panel)sender).Width / 8 * 7, ((Panel)sender).Height / 2));
                e.Graphics.DrawString(((Panel)sender).Tag.ToString().Split('|')[0], myFont, BrushBlack, 0, (float)(((Panel)sender).Height / 2));
            }
            
        }

        private void frmEditor_Paint(object sender, PaintEventArgs e)
        {
            
        }

        private void LoadDefaultTexture()
        {
            StreamReader sr = new StreamReader("def.texture");

            
            while (!sr.EndOfStream)
            {
                string l = sr.ReadLine();
                int key = 0;
                FileStream fs = new FileStream(l.Split('|')[1], FileMode.Open);
                list_Textures.Add(Convert.ToInt32(l.Split('|')[0]), Texture2D.FromStream(graphics, fs));
                list_KeysTextures.Add(_numberOfTexture, Convert.ToInt32(l.Split('|')[0]));
                fs.Close();

                //Ajout d'un panel.
                key = Convert.ToInt32(l.Split('|')[0]);
                if (key >= 0 && key <= 200)
                {
                    addControlToWalls(key.ToString(), l.Split('|')[1]);
                }
                else
                    if (key >= 201 && key <= 500)
                    {
                        addControlToTextures(key.ToString(), l.Split('|')[1]);
                    }
                    else
                        if (key >= 501)
                        {
                            addControlToItems(key.ToString(), l.Split('|')[1]);
                        }
               

                _numberOfTexture++;
                //Ajout du file dans la loadList par default.
                ListOfLoadedFiles.Add(l.Split('|')[1]);
            }
            foreach (Panel p in listPanel)
            {               
                p.ContextMenuStrip = cMenuStripClickPanel;
                p.MouseClick += new System.Windows.Forms.MouseEventHandler(EventPanel_Click);
                p.Paint += new System.Windows.Forms.PaintEventHandler(EventPanel_Paint);
               
            }            
         
        }

        private void frmEditor_Load(object sender, EventArgs e)
        {

        }

        //Load une texture et l'ajoute à la liste.
        private void loadFromFileToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofiledialog = new OpenFileDialog();
            DialogResult dr;
            
            

            string filename = "";

            dr = ofiledialog.ShowDialog();
            if (dr == DialogResult.OK)
            {
                filename = ofiledialog.FileName;
                ofiledialog.Dispose();
                AddTexture(filename);
            }
        }

        private void AddTexture(string _filename)
        {
            frmAddTexture frmAText;
            DialogResult dr;
            string filename = _filename;
            FileStream fs;
            
            frmAText = new frmAddTexture(filename,list_KeysTextures);
            dr = frmAText.ShowDialog();

            if (dr == DialogResult.Yes)
            {
                fs = new FileStream(filename, FileMode.Open);

                list_Textures.Add(frmAText.noText, Texture2D.FromStream(graphics, fs));
                list_KeysTextures.Add(_numberOfTexture, frmAText.noText);
                ListOfLoadedFiles.Add(filename);
                fs.Dispose();
                //Ajout d'un panel.

                if (frmAText.noText >= 0 && frmAText.noText <= 200)
                {
                    addControlToWalls(frmAText.noText.ToString(), filename);
                }
                else
                    if (frmAText.noText >= 201 && frmAText.noText <= 500)
                    {
                        addControlToTextures(frmAText.noText.ToString(), filename);
                    }
                    else
                        if (frmAText.noText >= 501)
                        {
                            addControlToItems(frmAText.noText.ToString(), filename);
                        }
              
                listPanel[listPanel.Count() - 1].MouseClick += new System.Windows.Forms.MouseEventHandler(EventPanel_Click);
                listPanel[listPanel.Count() - 1].Paint += new System.Windows.Forms.PaintEventHandler(EventPanel_Paint);
                listPanel[listPanel.Count() - 1].ContextMenuStrip = cMenuStripClickPanel;

                _numberOfTexture++;
            }
        }

        private void DeleteTexture(int key,string file)
        {
            bool isdeleted = false;
            int temporaryKey = 0;
            string temporaryFile = "";
            for (int i = 0; i <= list_KeysTextures.Count(); i++)
            {

                if (isdeleted)
                {
                    temporaryKey = list_KeysTextures[i];

                    list_KeysTextures.Remove(i);
                    list_KeysTextures.Add(i - 1, temporaryKey);
                   
                }
                else
                {
                    if (list_KeysTextures[i] == key)
                    {
                        list_Textures.Remove(key);
                        list_KeysTextures.Remove(i);
                        isdeleted = true;
                        
                    }
                    if (ListOfLoadedFiles[i] == file)
                    {
                        ListOfLoadedFiles.RemoveAt(i);
                        
                    }
                }
            }
        }

        private void ChangeID(int oldkey, int newkey,string file)
        {
          
            Texture2D temporarytext2d;
            temporarytext2d = list_Textures[oldkey];

            DeleteTexture(oldkey, file);
            _numberOfTexture--;
            list_Textures.Add(newkey, temporarytext2d);
            list_KeysTextures.Add(_numberOfTexture, newkey);
            ListOfLoadedFiles.Add(file);
            _numberOfTexture++;
            GetOldID = oldkey;
            GetNewID = newkey;
            _IDChanged = true;
            
        }

        private void loadFromFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbdialog = new FolderBrowserDialog();
            DialogResult dr = new DialogResult();
            string[] files;

            dr = fbdialog.ShowDialog();
            if (dr == DialogResult.OK)
            {
                files = Directory.GetFiles(fbdialog.SelectedPath,"*.png");
                for (int i = 0; i < files.Count(); i++)
                {
                    AddTexture(files[i]);
                }
            }
        }

        private void saveTexturesAsToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFD = new SaveFileDialog();
            saveFD.AddExtension = true;
            saveFD.DefaultExt = ".texture";
            DialogResult dr;
            string fileName;

            dr = saveFD.ShowDialog();
            if (dr == DialogResult.OK)
            {
                fileName = saveFD.FileName;
                //Sauvegarde de la liste dans def.texture
                StreamWriter sw = new StreamWriter(fileName);
                string line;
                for (int i = 0; i < list_Textures.Count(); i++)
                {

                    line = list_KeysTextures[i] + "|" + ListOfLoadedFiles[i];
                    sw.WriteLine(line);

                }
                sw.Close();
            }
        }

        public void SaveTexture()
        {
            //Sauvegarde de la liste dans def.texture

            DialogResult dr = new DialogResult();

            dr = MessageBox.Show("Voulez-vous sauvegarder les Textures ajoutées dans les textures par default?", "Validation", MessageBoxButtons.YesNo);
            if (dr == DialogResult.Yes)
            {
                StreamWriter sw = new StreamWriter("def.texture");
                string line;
                for (int i = 0; i < list_Textures.Count(); i++)
                {

                    line = list_KeysTextures[i] + "|" + ListOfLoadedFiles[i];
                    sw.WriteLine(line);

                }
                sw.Close();
            }
        }

        //Edit le ID d'une texture.
        private void editIDToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string file;
            int oldID;
            frmChangeID frmID = new frmChangeID(list_KeysTextures);
            DialogResult dr = new DialogResult();

            if (PanelSelected != null)
            {
                if (PanelSelected.Tag.ToString().Split('|')[0] == "0")
                {
                    MessageBox.Show("The mighty wizard of Kuka Keep don't want you to change the ID of this texture");
                    return;
                }
                file = PanelSelected.Tag.ToString().Split('|')[1];
                oldID = Convert.ToInt32(PanelSelected.Tag.ToString().Split('|')[0]);
                 dr = frmID.ShowDialog();
                 if (dr == DialogResult.Yes)
                 {
                     ChangeID(oldID,frmID.ID,file);
                     _selectedIndex = frmID.ID;
                     PanelSelected.Tag = frmID.ID.ToString() + "|" + PanelSelected.Tag.ToString().Split('|')[1];
                     this.Refresh();
                     ResetPanel();
                 }
                
            }
        }

        //Supprime une texture
        private void supprimerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult dr = new DialogResult();
            if (PanelSelected != null)
            {
                if (PanelSelected.Tag.ToString().Split('|')[0] == "0")
                {
                    MessageBox.Show("The mighty wizard of Kuka Keep don't want you to delete this texture");
                    return;
                }
                dr = MessageBox.Show("Êtes-vous sur de vouloir supprimer cette texture? La texture sera supprimer sur le panel XNA.", "Validation", MessageBoxButtons.YesNo);
                if (dr == DialogResult.Yes)
                {
                    DeleteTexture(Convert.ToInt32(PanelSelected.Tag.ToString().Split('|')[0]), PanelSelected.Tag.ToString().Split('|')[1]);
                    GetOldID = Convert.ToInt32(PanelSelected.Tag.ToString().Split('|')[0]);
                    listPanel.Remove(PanelSelected);
                    this.Controls.Remove(PanelSelected);
                    PanelSelected.Dispose();
                    _TextureDeleted = true;
                    PanelSelected = null;
                    _selectedIndex = 0;
                    _numberOfTexture--;
                    ResetPanel();
                }
            }
        }

        private void cMenuStripClickPanel_Opening(object sender, CancelEventArgs e)
        {
            if (cMenuStripClickPanel.SourceControl is Panel)
            {
                PanelSelected = ((Panel)cMenuStripClickPanel.SourceControl);                
            }
        }


        //Affiche l'id ou la cache.
        private void showIDToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (showID)
            {
                showID = false;
                showIDToolStripMenuItem.Text = "Show ID";
            }
            else
                if (!showID)
                {
                    showID = true;
                    showIDToolStripMenuItem.Text = "Hide ID";
                }
            this.Refresh();
        }

        //Cache la grille ou l'affiche
        private void hideGridToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ShowGrid)
            {
                ShowGrid = false;
                hideGridToolStripMenuItem.Text = "Show Grid";
            }
            else
                if (!ShowGrid)
                {
                    ShowGrid = true;
                    hideGridToolStripMenuItem.Text = "Hide Grid";
                }
        }

        private void addControlToItems(string key,string file)
        {
            listPanel.Add(AddControls.addPanel(width, height, topItems, leftItems,key, file));
            tabItems.Controls.Add(listPanel[listPanel.Count() - 1]);
            leftItems += 60;
            if (this.Width - 80 <= leftItems)
            {
                leftItems = 20;
                topItems += 60;
            }
        }

        private void addControlToWalls(string key,string file)
        {
            listPanel.Add(AddControls.addPanel(width, height, topWalls, leftWalls, key, file));
            tabWalls.Controls.Add(listPanel[listPanel.Count() - 1]);
            leftWalls += 60;
            if (this.Width - 80 <= leftWalls)
            {
                leftWalls = 20;
                topWalls += 60;
            }
        }

        private void addControlToTextures(string key, string file)
        {
            listPanel.Add(AddControls.addPanel(width, height, topTextures, leftTextures, key, file));
            tabTextures.Controls.Add(listPanel[listPanel.Count() - 1]);
            leftTextures += 60;
            if (this.Width - 80 <= leftTextures)
            {
                leftTextures = 20;
                topTextures += 60;
            }
        }

        private void ResetPanel()
        {
             topItems = 30;
             leftItems = 20;
             topWalls = 30;
             leftWalls = 20;
             topTextures = 30;
             leftTextures = 20;

             tabTextures.Controls.Clear();
             tabItems.Controls.Clear();
             tabWalls.Controls.Clear();
             listPanel.Clear();
           

                 for (int i = 0; i < ListOfLoadedFiles.Count(); i++)
                 {
                     if (list_KeysTextures[i] >= 0 && list_KeysTextures[i] <= 200)
                     {
                         addControlToWalls(list_KeysTextures[i].ToString(), ListOfLoadedFiles[i]);
                     }
                     else
                         if (list_KeysTextures[i] >= 201 && list_KeysTextures[i] <= 500)
                         {
                             addControlToTextures(list_KeysTextures[i].ToString(), ListOfLoadedFiles[i]);
                         }
                         else
                             if (list_KeysTextures[i] > 500)
                             {
                                 addControlToItems(list_KeysTextures[i].ToString(), ListOfLoadedFiles[i]);
                             }
                 }

           

             foreach (Panel p in listPanel)
             {
                 p.ContextMenuStrip = cMenuStripClickPanel;
                 p.MouseClick += new System.Windows.Forms.MouseEventHandler(EventPanel_Click);
                 p.Paint += new System.Windows.Forms.PaintEventHandler(EventPanel_Paint);
             }
        }

        private void btnLeftLayer_Click(object sender, EventArgs e)
        {
            int var = 0;
            if (!cbAllLayers.Checked)
            {
                if (int.TryParse(txtNoLayers.Text, out var))
                {
                    if (var == 1)
                    {
                        GetIDLayers = 3;
                        txtNoLayers.Text = GetIDLayers.ToString();
                    }
                    else
                    {
                        GetIDLayers--;
                        txtNoLayers.Text = GetIDLayers.ToString();
                    }
                }
            }
            else
            {
                txtNoLayers.Text = "";
            }

        }

        private void btnRightLayer_Click(object sender, EventArgs e)
        {
            int var = 0;
            if (!cbAllLayers.Checked)
            {
                if (int.TryParse(txtNoLayers.Text, out var))
                {
                    if (var == 3)
                    {
                        GetIDLayers = 1;
                        txtNoLayers.Text = GetIDLayers.ToString();
                    }
                    else
                    {
                        GetIDLayers++;
                        txtNoLayers.Text = GetIDLayers.ToString();
                    }
                }
            }
            else
            {
                txtNoLayers.Text = "";
            }
        }

        private void cbAllLayers_CheckedChanged(object sender, EventArgs e)
        {
            if (!cbAllLayers.Checked)
            {
                GetIDLayers = 1;
                txtNoLayers.Text = GetIDLayers.ToString();
            }
            else
            {
                GetIDLayers = 4;
                txtNoLayers.Text = "";
            }
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IsLoading = true;
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IsSaving = true;
        }

        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IsSaving = true;
        }

        private void loadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IsLoading = true;
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ExitSig = true;
        }

        private void clearMapToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ClearSig = true;
        }

        private void editSizeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (frmEd.ShowDialog() == DialogResult.OK)
            {
                HasMapChangedDimensions = true;
            }
        }
    }
}
